﻿using MediatR;
using S.Common.ApiResult;
using S.PurchaseAndSales.Domain.Model;
using S.PurchaseAndSales.Read.Api.Application.Command.SheepSaleCommand;
using S.PurchaseAndSales.Infrastructure.Interface.SalesForm;

namespace S.PurchaseAndSales.Read.Api.Application.CommandHandlers.SheepSaleHandler
{
    public class GetSheepListHandler : IRequestHandler<GetSheepListCommand, ApiResult<List<SheepSaleModel>>>
    {
        private readonly ISheepSaleRepository sheepSale;

        public GetSheepListHandler(ISheepSaleRepository sheepSale)
        {
            this.sheepSale = sheepSale;
        }

        public async Task<ApiResult<List<SheepSaleModel>>> Handle(GetSheepListCommand request, CancellationToken cancellationToken)
        {
            var list = sheepSale.GetAllAsync().Result.OrderByDescending(m=>m.CreateDate).ToList();
            //查询条件
            if (!string.IsNullOrWhiteSpace(request.StateDate) && !string.IsNullOrWhiteSpace(request.EndDate))
            {
                list = list.Where(x => x.SaleDate > Convert.ToDateTime(request.StateDate) && x.SaleDate <= Convert.ToDateTime(request.EndDate).AddDays(1)).OrderByDescending(m=>m.CreateDate).ToList();
            }
            //客户
            if(request.CustomId!=0)
            {
                list=list.Where(m=>m.CustomerInformationId==request.CustomId).ToList();
            }
            //耳号
            if (!string.IsNullOrWhiteSpace(request.EarTag))
            {
                list = list.Where(x => x.EarTag.Contains(request.EarTag)).ToList();
            }
            //单据号
            if (!string.IsNullOrEmpty(request.DocNum))
            {
                list=list.Where(m=>m.DocNumber.Contains(request.DocNum)).ToList();
            }
            //部门
            if (request.DocId != 0)
            {
                list=list.Where(m=>m.DocId==request.DocId).ToList();
            }
            //收货地址
            if (!string.IsNullOrEmpty(request.Address))
            {
                list=list.Where(m=>m.Address.Contains(request.Address)).ToList();
            }
            //销售员
            if (request.SaleId != 0)
            {
                list=list.Where(m=>m.SaleId==request.SaleId).ToList();
            }
            //审核状态
            if (request.State != 0)
            {
                list=list.Where(m=>m.CheckState==request.State).ToList();
            }
            ApiResult<List<SheepSaleModel>> result = new ApiResult<List<SheepSaleModel>>();

            //总页数、总条数
            int totalCount = list.Count;
            int pageCount = (int)Math.Ceiling(totalCount * 1.0 / request.PageSize);
            result.totalCount = totalCount;
            result.pageCount = pageCount;
            // 对列表进行分页处理
            result.Data = list.Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();

            return result;
        }
    }
}
